package hd

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"sync"
)

var urlCacheMap = make(map[string]string, 0)
var urlCacheLock = sync.Mutex{}

// GetJointActivityUrl 获取到C端参与活动的url，带token
func GetJointActivityUrl(aid, gameId int, uid string) (string, error) {
	////getCode
	//code, err := GetCode("", "testUid", "", "", "")
	//if err != nil {
	//	fmt.Println("getCode rer")
	//}
	//partnerAccessToken, err := GetPartnerAccessToken(code)  旧方式获取token
	partnerAccessToken, err := GetPartnerAccessTokenDirect(uid, "", "", "")
	if err != nil {
		fmt.Println("getToken err")
		return "", err
	}
	activityUrl, err := GetActivityUrl(aid, gameId)
	if err != nil {
		fmt.Println("GetActivityUrl err")
		return "", err
	}
	joinActiveUrl := activityUrl + "&partner_access_token=" + partnerAccessToken.AccessToken
	return joinActiveUrl, nil
}

func GetActivityUrl(aid, gameId int) (string, error) {
	cacheKey := "activityUrl:" + strconv.Itoa(aid) + ":" + strconv.Itoa(gameId)

	cacheUrl, ok := urlCacheMap[cacheKey]
	if ok {
		return cacheUrl, nil
	}
	urlCacheLock.Lock()
	defer urlCacheLock.Unlock()
	//锁内doubleCheck
	cacheUrl, ok = urlCacheMap[cacheKey]
	if ok {
		return cacheUrl, nil
	}
	info, err := GetActivitiesInfo(aid, gameId)
	if err != nil {
		fmt.Println("GetActivitiesInfo err")
		return "", err
	}
	fmt.Println("log GetActivitiesInfo")
	//自行判断接口返回值的code
	var errCode = fmt.Sprintf("%v", info["code"])
	if errCode != "0" {
		return "", errors.New("GetActivitiesInfo err")
	}
	activeUrl := info["data"].(map[string]interface{})["activityUrl"]
	urlCacheMap[cacheKey] = activeUrl.(string)
	return activeUrl.(string), nil
}

// GetActivitiesInfo 获取某个活动的源地址
func GetActivitiesInfo(aid, gameId int) (map[string]interface{}, error) {
	token, err := GetAccessToken()
	if err != nil {
		fmt.Println("getAccessToken", err)
		return nil, err
	}
	client := &http.Client{}
	urlValues := url.Values{}
	urlValues.Set("aid", strconv.Itoa(aid))
	urlValues.Set("activityId", strconv.Itoa(gameId))
	reqUrl, err := url.Parse(ApiUrl + "/open-api/activities/one")
	if err != nil {
		return nil, err
	}
	reqUrl.RawQuery = urlValues.Encode()
	req, _ := http.NewRequest("GET", reqUrl.String(), nil)
	req.Header.Add("Authorization", "Bearer "+token.AccessToken)
	resp, _ := client.Do(req)
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			fmt.Println("close err")
		}
	}(resp.Body)
	body, _ := ioutil.ReadAll(resp.Body)
	jsonMap := make(map[string]interface{})
	err = json.Unmarshal(body, &jsonMap)
	if err != nil {
		return nil, err
	}
	return jsonMap, nil
}
